package com.xialinrui.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xialinrui.dto.TodoDto;
import com.xialinrui.entity.*;
import com.xialinrui.service.*;
import com.xialinrui.vo.AffairAddTodoVo;
import com.xialinrui.vo.TodoCancelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xialinrui
 */
@RestController
@Slf4j
@RequestMapping("/affair")
public class AffairController {

    @Resource
    private AffairService affairService;
    @Resource
    private AcquirementService acquirementService;
    @Resource
    private UserService userService;
    @Resource
    private TimeQuantumService timeQuantumService;

    @Resource
    private IncomeService incomeService;

    /**
     * 添加一个事务
     *
     * @param affair
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<Map<String, Long>> addAffair(@RequestBody Affair affair) {
        HashMap<String, Long> resMap = new HashMap<>(1);
        affairService.addOneAffair(affair);
        resMap.put("id", affair.getId());
        return new ResponseResult(200, "添加成功", resMap);
    }

    /**
     * 在一个事务中添加一个或者多个任务
     *
     * @param affairAddTodoVo
     * @return
     */
    @PutMapping("/add/todo")
    public ResponseResult addTodoToAffair(@RequestBody AffairAddTodoVo affairAddTodoVo) {
        for (Long id : affairAddTodoVo.getTodoIds()) {
            affairService.addTodoToAffair(affairAddTodoVo.getAffairId(), id);
        }
        return new ResponseResult(200, "添加成功");
    }

    /**
     * 编辑备注
     *
     * @param affair
     * @return
     */
    @PostMapping("/edit/remarks")
    public ResponseResult editRemarks(@RequestBody Affair affair) {
        UpdateWrapper<Affair> affairUpdateWrapper = new UpdateWrapper<>();
        affairUpdateWrapper.set("remarks", affair.getRemarks()).eq("id", affair.getId());
        affairService.update(affairUpdateWrapper);
        return new ResponseResult(200, "编辑成功");
    }

    /**
     * 取消任务
     *
     * @param todoCancelVo
     * @return
     */
    @DeleteMapping("/todo/delete")
    public ResponseResult deleteAffair(@RequestBody TodoCancelVo todoCancelVo) {
        Long affairId = todoCancelVo.getAffairId();
        for (Long todoId : todoCancelVo.getTodoIds()) {
            affairService.deleteAffair(affairId, todoId);
        }
        return new ResponseResult(200, "删除成功");
    }

    /**
     * 根据事务id设置学习时长
     *
     * @param id 事务的id
     * @return 返回今日学习总时长
     */
    @PutMapping("/study/time")
    public ResponseResult<Integer> setStudyTime(@RequestParam Long id, @RequestParam Integer realTime) {
        //更新用户学习总时长
        //由于要用到事务原始的表中的数据，所以不能先改事务的表
        userService.updateStudyingTime(id, realTime);
        //修改今日的获得
        acquirementService.addAcquireByAffairIdAndTime(id, realTime);
        //修改用户总获得
        userService.addAcquireByTime(realTime);
        //更新并获取获取今天的总时长
        Integer todayStudyingTime = acquirementService.getDailyStudyTime(id, realTime);
        //将时长数据保存到数据库
        UpdateWrapper<Affair> affairUpdateWrapper = new UpdateWrapper<>();
        affairUpdateWrapper.set("real_time", realTime).eq("id", id);
        affairService.update(affairUpdateWrapper);
        //如果数据库中没有就直接创建
        Affair affair = affairService.getById(id);
        User user = userService.getById(1L);
        Double money = user.getGetMoneyPerMinute() * affair.getRealTime();
        if (affair.getIncomeId() == null) {
            if (affair.getRealTime() != 0) {
                Income income = new Income(null, new java.util.Date(), 2L, affair.getDate().toString() + affair.getStartTime().toString() +"~"+affair.getEndTime().toString(), null);
                income.setMoney(money);
                incomeService.save(income);
                affair.setIncomeId(income.getId());
                affairService.updateById(affair);
            }
        } else {//如果数据库中有就修改一下值
            Income income = incomeService.getById(affair.getIncomeId());
            if (affair.getRealTime() == 0) {
                incomeService.removeById(income);
            } else {
                income.setMoney(money);
                incomeService.updateById(income);
            }
        }
        //返回设置成功信息
        return new ResponseResult(200, "设置成功", todayStudyingTime);
    }

    /**
     * 根据事务id删除事务
     *
     * @param affairId
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseResult delete(@RequestParam Long affairId) {
        List<TodoDto> todoDtos = affairService.selectAllTodosByAffairId(affairId);
        if (todoDtos == null || todoDtos.size() == 0) {
            affairService.deleteAffairById(affairId);
            return new ResponseResult(200, "删除成功");
        }
        return new ResponseResult(400, "请先清空该时间段的任务再删除");
    }

    /**
     * 设置默认时间
     *
     * @param timeQuantumList
     * @return
     */
    @PutMapping("/default/time/quantum")
    public ResponseResult setTimeQuantum(@RequestBody List<List<Time>> timeQuantumList) {
        timeQuantumService.deleteLast();
        timeQuantumService.insert(timeQuantumList);
        return new ResponseResult(200, "成功");
    }

    /**
     * 查询推荐时间段
     *
     * @return
     */
    @GetMapping("/recommend/time/quantum")
    public ResponseResult<List<TimeQuantum>> recommendTimeQuantum() {
        QueryWrapper<TimeQuantum> timeQuantumQueryWrapper = new QueryWrapper<>();
        timeQuantumQueryWrapper.eq("status", 2).orderByAsc("start").orderByAsc("end");
        List<TimeQuantum> resList = timeQuantumService.list(timeQuantumQueryWrapper);
        return new ResponseResult<>(200, "查询成功", resList);
    }

    /**
     * 查询默认时间段
     *
     * @return
     */
    @GetMapping("/default/time/quantum")
    public ResponseResult<List<TimeQuantum>> defaultTimeQuantum() {
        QueryWrapper<TimeQuantum> timeQuantumQueryWrapper = new QueryWrapper<>();
        timeQuantumQueryWrapper.eq("status", 1).orderByAsc("start").orderByAsc("end");
        List<TimeQuantum> resList = timeQuantumService.list(timeQuantumQueryWrapper);
        return new ResponseResult<>(200, "查询成功", resList);
    }

    /**
     * 根据日期初始化所有事务
     *
     * @param date
     * @return
     */
    @PostMapping("/init/daily")
    public ResponseResult<List<Affair>> init(@RequestParam Date date, @RequestParam Integer weekNumber) {
        QueryWrapper<TimeQuantum> timeQuantumQueryWrapper = new QueryWrapper<>();
        timeQuantumQueryWrapper.eq("status", 1).orderByAsc("start").orderByAsc("end");
        List<TimeQuantum> list = timeQuantumService.list(timeQuantumQueryWrapper);
        List<Affair> resList = new ArrayList<>();
        for (TimeQuantum timeQuantum : list) {
            Affair cur = new Affair(null, date, weekNumber, timeQuantum.getStart(), timeQuantum.getEnd(), 0, "", null);
            affairService.addOneAffair(cur);
            resList.add(cur);
        }
        return new ResponseResult<>(200, "初始化当天事务成功", resList);
    }

    @GetMapping("/get/acquirement")
    public ResponseResult<Map<String, Object>> getAcquirement(@RequestParam Date date) {
        QueryWrapper<Acquirement> acquirementQueryWrapper = new QueryWrapper<>();
        acquirementQueryWrapper.eq("date", date);
        Acquirement acquirement = acquirementService.getOne(acquirementQueryWrapper);
        Map<String, Object> resMap = new HashMap<>(3);
        resMap.put("studyTime", acquirement.getStudyTime());
        resMap.put("loveNumbers", acquirement.getLoveNumbers());
        resMap.put("moneyNumbers", acquirement.getMoneyNumbers());
        return new ResponseResult<>(200, "查询成功", resMap);
    }

}
